package com.example.xinlijiankangsys.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan("com.example.xinlijiankangsys.mapper")
public class MybatisConfig {
    @Autowired
    private DataSource dataSource; // 注入数据源

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);

        // 设置Mapper文件路径（如果使用XML Mapper）
//        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
//                .getResources("classpath:mapper/*.xml")); // 如果有XML Mapper文件

        // 如果需要设置其他MyBatis属性，可以通过以下方式进行设置
        // MyBatisConfiguration myBatisConfiguration = new MyBatisConfiguration();
        // sessionFactory.setConfiguration(myBatisConfiguration);

        return sessionFactory.getObject();
    }

    @Bean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}
